package com.hmsm.server.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.logging.LogFactory;

public class URLHelp {

	private static final org.apache.commons.logging.Log log = LogFactory.getLog(URLHelp.class);
	
	/**
	 * 请求URL，并返回请求内容
	 * 
	 * @param urlAddr
	 * @return
	 * @throws Exception 
	 */
	public String requestRul(String urlAddr) throws Exception {
		return requestRul(urlAddr, "POST", "UTF-8");
	}
	
	/**
	 * 请求URL，并返回请求内容
	 * 
	 * @param urlAddr
	 * @return
	 * @throws Exception 
	 */
	public String requestRul(String urlAddr, String method, String charsetName) throws Exception {
		String strResult = null;

		java.net.URL url = new URL(urlAddr);
		URLConnection urlConnection = url.openConnection();
		if(urlConnection==null){
			Log.logError(this, "无法获取URL请求："+urlAddr);
			return strResult;
		}
		urlConnection.setDoOutput(true);
		log.debug("urlConnection.class="+urlConnection.getClass());

		if (urlConnection instanceof HttpURLConnection){
			((HttpURLConnection)urlConnection).setRequestMethod(method);
		}else if(urlConnection instanceof HttpsURLConnection){
			((HttpsURLConnection)urlConnection).setRequestMethod(method);
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), charsetName));
		strResult = reader.readLine();

		if (urlConnection != null) {
			if (urlConnection instanceof HttpURLConnection){
				((HttpURLConnection)urlConnection).disconnect();
			}else if(urlConnection instanceof HttpsURLConnection){
				((HttpsURLConnection)urlConnection).disconnect();
			}
		}
		
		return strResult;
	}
	
	/**
	 * URL地址请求 舒俊
	 * 
	 * @param urlAddr
	 * @return 2014-1-16
	 */
	public String getUrl(String urlAddr) {
		return getUrl(urlAddr, "GBK");
	}
	
	/**
	 * URL地址请求 舒俊
	 * 
	 * @param urlAddr
	 * @return 2014-1-16
	 */
	public String getUrl(String urlAddr, String encoding) {
		
		if (encoding==null||encoding.length()==0){
			encoding = "GBK";
		}
		URL url;
		String temp;
		final StringBuffer sb = new StringBuffer();
		try {
			url = new URL(urlAddr);
			final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), encoding));// 读取网页全部内容
			while ((temp = in.readLine()) != null) {
				sb.append(temp);
			}
			in.close();
		} catch (final MalformedURLException me) {
			// 你输入的URL格式有问题！请仔细输入
			me.getMessage();
			Log.logError(this,"你输入的URL格式有问题！请仔细输入:" + me.toString());
		} catch (final IOException e) {
			e.printStackTrace();
			Log.logError(this,"异常：" + e.toString());
		}
		return sb.toString();
	}
	
	/**
	 * post请求 舒俊
	 * 
	 * @param urlAddr
	 * @param data
	 * @return 2014-1-16
	 */
	public String postURL(String urlAddr, String data, String charsetName) {
		
		if (charsetName==null||charsetName.length()==0){
			charsetName = "GBK";
		}

		try {
			URL url = new URL(urlAddr);
			try {
				HttpURLConnection http = (HttpURLConnection) url.openConnection();
				http.setRequestMethod("POST");
				http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				http.setDoOutput(true);
				http.setDoInput(true);
				System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
				System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
				http.connect();
				if (data!=null){
					OutputStream os = http.getOutputStream();
					os.write(data.getBytes(charsetName));// 传入参数
					os.flush();
					os.close();
				}
				InputStream is = http.getInputStream();
				int size = is.available();
				byte[] jsonBytes = new byte[size];
				is.read(jsonBytes);
				String message = new String(jsonBytes, charsetName);
				return message;
			} catch (IOException e) {
				e.printStackTrace();
				log.error("异常：" + e.toString());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			log.error("异常：" + e.toString());
		}
		return "";
	}
	
	/**
	 * post请求 舒俊
	 * 
	 * @param urlAddr
	 * @param data
	 * @return 2014-1-16
	 */
	public String postJson(String urlAddr, String data, String charsetName) {
		
		if (charsetName==null||charsetName.length()==0){
			charsetName = "GBK";
		}

		try {
			URL url = new URL(urlAddr);
			try {
				HttpURLConnection http = (HttpURLConnection) url.openConnection();
				http.setRequestMethod("POST");
				http.setRequestProperty("Content-Type", "application/json");
				http.setDoOutput(true);
				http.setDoInput(true);
				System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
				System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
				http.connect();
				if (data!=null){
					OutputStream os = http.getOutputStream();
					os.write(data.getBytes(charsetName));// 传入参数
					os.flush();
					os.close();
				}
				InputStream is = http.getInputStream();
				int size = is.available();
				byte[] jsonBytes = new byte[size];
				is.read(jsonBytes);
				String message = new String(jsonBytes, charsetName);
				return message;
			} catch (IOException e) {
				e.printStackTrace();
				log.error("异常：" + e.toString());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			log.error("异常：" + e.toString());
		}
		return "";
	}

}
